package com.freemarker.exception;

import freemarker.core.Environment;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.Writer;

/**
 * Created by 苏犇 on 2019/1/8. <br>
 */
public class FreemarkerExceptionHandler implements TemplateExceptionHandler {

    private static Logger logger = Logger.getLogger(FreemarkerExceptionHandler.class);

    @Override
    public void handleTemplateException(TemplateException e, Environment environment, Writer writer) throws TemplateException {
        logger.error("[Freemarker Exception: " + e.getMessage());
        String missingVariable = "undefined";
        try {
            String [] tmp = e.getMessageWithoutStackTop().split("\n ");
            if (tmp.length > 1)
                tmp = tmp[1].split(" ");
            if (tmp.length > 1)
                missingVariable = tmp[1];

            writer.write("[出错了，请联系网站管理员：${ " + missingVariable
                    + "}]");
            logger.error("[出错了，请联系网站管理员]", e);
        } catch (IOException e1) {
            throw new TemplateException(
                    "Failed to print error message. Cause: " + e1, environment);

        }


    }
}
